<?php

namespace EasySwoole\EasySwoole;


use App\Biz\AwardsBiz;
use App\Biz\StageBiz;
use App\Biz\UserBiz;
use App\Process\QueueProcess;

use App\Tars\TarsManage;
use EasySwoole\Component\Di;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Db\Connection;

use EasySwoole\Redis\Config\RedisConfig;
use EasySwoole\RedisPool\Redis;
use EasySwoole\Socket\Dispatcher;
use EasySwoole\WeChat\WeChat;
use priestll\easyswoole\queue\Queue;
use priestll\easyswoole\websocket\WebSocketEvent;
use priestll\easyswoole\websocket\WebSocketParser;
use priestll\easyswoole\wechat\WeChatManager;


class EasySwooleEvent implements Event
{

    public static function initialize()
    {
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');

        $config = \EasySwoole\EasySwoole\Config::getInstance();

        /*################ MYSQL INIT START ##################*/
        //注册MYSQL
        $dbconfig = new \EasySwoole\ORM\Db\Config($config->getConf('MYSQL'));

        DbManager::getInstance()->addConnection(new Connection($dbconfig));
        /*################ MYSQL INIT END ##################*/

        /*################ REDIS INIT START##################*/
        //注册REDIS
        $redisConfig = new RedisConfig($config->getConf('REDIS'));
        $redis = Redis::getInstance();
        $redisPoolConfig = $redis->register('redis', $redisConfig);

        $redisPoolConfig->setMinObjectNum($config->getConf('REDIS.POOL_MIN_NUM'));

        $redisPoolConfig->setMaxObjectNum($config->getConf('REDIS.POOL_MAX_NUM'));

        /*################ REDIS INIT END##################*/

        /*################ QUEUE INIT START##################*/
        //注册QUEUE REUSY
        $redisConfig = new RedisConfig($config->getConf('QUEUE'));
        $redis = Redis::getInstance();
        $redisPoolConfig = $redis->register('queue', $redisConfig);
        $redisPoolConfig->setMinObjectNum($config->getConf('REDIS.POOL_MIN_NUM'));
        $redisPoolConfig->setMaxObjectNum($config->getConf('REDIS.POOL_MAX_NUM'));
        $driver = new \EasySwoole\Queue\Driver\Redis(\EasySwoole\RedisPool\Redis::getInstance()->get('queue'));
        Queue::getInstance($driver);
        //注册一个消费者
        \EasySwoole\Component\Process\Manager::getInstance()->addProcess(new QueueProcess());
        /*################ QUEUE INIT END##################*/

        /*################ DI INIT START##################*/
        //BIZ
        Di::getInstance()->set('USER_BIZ', UserBiz::class);
        Di::getInstance()->set('STAGE_BIZ', StageBiz::class);
        Di::getInstance()->set('AWARDS_BIZ', AwardsBiz::class);

        /*################ DI INIT END##################*/
    }

    public static function mainServerCreate(EventRegister $register)
    {

        /*################ websocket控制器 START ##################*/
        // 创建一个 Dispatcher 配置
        $conf = new \EasySwoole\Socket\Config();
        // 设置 Dispatcher 为 WebSocket 模式
        $conf->setType(\EasySwoole\Socket\Config::WEB_SOCKET);
        // 设置解析器对象
        $conf->setParser(new WebSocketParser());
        // 创建 Dispatcher 对象 并注入 config 对象
        $dispatch = new Dispatcher($conf);
        // 给server 注册相关事件 在 WebSocket 模式下  on message 事件必须注册 并且交给 Dispatcher 对象处理
        $register->set(EventRegister::onMessage, function (\swoole_websocket_server $server, \swoole_websocket_frame $frame) use ($dispatch) {
            $dispatch->dispatch($server, $frame->data, $frame);
        });
        //自定义握手事件
        $websocketEvent = new WebSocketEvent();

        $register->set(EventRegister::onHandShake, function (\swoole_http_request $request, \swoole_http_response $response) use ($websocketEvent) {
            $websocketEvent->onHandShake($request, $response);
        });
        /*################ websocket控制器 END##################*/

        /*################ 微信配置 START ##################*/
        //微信配置
//        $weChatConfig = new \EasySwoole\WeChat\Config();
//        $weChatConfig->setTempDir(Config::getInstance()->getConf('TEMP_DIR'));
//
//        // 也可以使用这个方案
//        $configArray = [
//            'appId' => 'you appId',
//            'appSecret' => 'you appSecret',
//            'token' => 'you token',
//            'AesKey' => 'you AesKey',
//        ];
//        $weChatConfig->officialAccount($configArray);
//        // 注册WeChat对象到全局List
//        WeChatManager::getInstance()->register('wechat', new WeChat($weChatConfig));


        // 开放平台注册
//        $configArray = [
//            'componentAppId'     => 'you componentAppId',
//            'componentAppSecret' => 'you componentAppSecret',
//            'token'     => 'you token',
//            'aesKey'    => 'you aesKey',
//        ];
//        $weChatConfig->openPlatform($configArray);
        //NetworkReleases::register($openPlatform);

        /*################ 微信配置 END ##################*/

        /*################ 定时器配置 START ##################*/
        $register->add(EventRegister::onWorkerStart, function (\swoole_server $server, $workerId) {

            if ($workerId == 0) {
//                \EasySwoole\Component\Timer::getInstance()->loop(7100 * 1000, function () {
//                    WeChatManager::getInstance()->weChat('wechat')->officialAccount()->accessToken()->refresh();
//                });
            //Tars定时上报

                \EasySwoole\Component\Timer::getInstance()->loop(3 * 1000, function () {
                    $tars = TarsManage::getInstance();
                    $masterPid = $tars->getMasterAlivePid();
                    var_dump($masterPid);
                    $tars->keepAlive($masterPid);
                });

            }
        });
        /*################ 定时器配置 END ##################*/

    }

    public static function onRequest(Request $request, Response $response): bool
    {
        // TODO: Implement onRequest() method.
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        // TODO: Implement afterAction() method.
    }
}